#include "game.h"

using namespace std;

void gobang_ui_init(char gobang_ui[][COL])
{
    memset(gobang_ui, ' ', ROW * COL);

    return;
}

void show_gobong_ui(char gobang_ui[][COL])
{
    cout << "   0 1 2 3 4 5 6 7 8 9 10 11 12 13 14" << endl;

    for (int i = 0; i < ROW; i++)
    {
        if (i <= 9)
        {
            cout << ' ' << i << ' ';
        }
        else
        {
            cout << i << ' ';
        }

        for (int j = 0; j < COL; j++)
        {
            cout << gobang_ui[i][j] << ' ';
        }

        cout << endl;
    }

    return;
}

int play_chess(char gobang_ui[][COL], int row, int col, char pawn)
{
    // 合法性判断
    if (gobang_ui[row][col] != ' ')
    {
        return -1;
    }

    gobang_ui[row][col] = pawn;

    return 1;
}

int check_victory(char gobang_ui[][COL], int row, int col, char pawn)
{
    // 方向：水平、垂直、主对角线、副对角线
    int d[2][4] = {{0, 1, 1, 1}, {1, 0, 1, -1}};

    int new_row = 0;
    int new_col = 0;
    int count = 0;

    // 遍历四个方向
    for (int i = 0; i < 4; i++)
    {
        count = 1;

        // 向一个方向查找
        for (int j = 1; j < 5; j++)
        {
            new_row = row + d[0][i] * j;
            new_col = col + d[1][i] * j;

            if (new_row < 0 || new_row >= ROW || new_col < 0 || new_col >= COL || gobang_ui[new_row][new_col] != pawn)
            {
                break;
            }

            count++;
        }

        // 向相反方向查找
        for (int j = 1; j < 5; j++)
        {
            new_row = row - d[0][i] * j;
            new_col = col - d[1][i] * j;

            if (new_row < 0 || new_row >= ROW || new_col < 0 || new_col >= COL || gobang_ui[new_row][new_col] != pawn)
            {
                break;
            }

            count++;
        }

        // 连续的棋子数量大于等于5，说明获胜
        if (count >= 5)
        {
            return 1;
        }
    }

    return 0;
}